// 医嘱项---医嘱项别名
import React from 'react';
import {Form, Button, Input, Table, Card, Popconfirm, Select, Divider, message} from 'antd';
import { $http } from 'containers/config/https';
import { Util } from 'tools/index';

const EditableContext = React.createContext();

class EditableCell extends React.Component {
    getInput = () => {
        if (this.props.inputType === 'select') {
            return <Select style={{width: '80%'}}></Select>;
        }
        return <Input style={{width: '80%'}} />;
    };

    renderCell = ({ getFieldDecorator }) => {
        const {
            editing,
            dataIndex,
            title,
            inputType,
            record,
            index,
            children,
            ...restProps
        } = this.props;
        return (
        <td {...restProps}>
            {editing ? (
                <Form.Item style={{ margin: 0 }}>
                    {getFieldDecorator(dataIndex, {
                    rules: [
                        {
                        required: (dataIndex === 'name' || dataIndex === 'age') ? true : false,
                        message: `${title+ (JSON.parse(window.sessionStorage.userData).language == 'EN' ? ' Can not be empty!' : '不能为空!')}`,
                        },
                    ],
                    initialValue: record[dataIndex],
                    })(this.getInput())}
                </Form.Item>
            ) : (
                children
            )}
        </td>
        );
    };

    render() {
        return <EditableContext.Consumer>{this.renderCell}</EditableContext.Consumer>;
    }
}

class ADADoctorAdviceAlias extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
            dataSource: [],
            columns: [],
            editingKey: '',
            language: JSON.parse(window.sessionStorage.userData),
        }
    }

    componentDidMount() {
        this.props.onRef(this);
        this.getColumnsData();
    }

    handleValidateFields = () => {
        this.props.receiveSubcomponentsValue(this.state.dataSource, 'doctorAdviceAlias')
    }

    // 获取表格数据
    getTableData = (tableData) => {
        let dataSource = JSON.parse(JSON.stringify(tableData));
        for(var i = 0; i < dataSource.length; i++) {
            dataSource[i].key = i + 1;
        }
        this.setState({dataSource});
    }

    // 获取表头数据
    getColumnsData = () => {
        let columns = [
            {
                title: this.state.language.language == 'EN'?'Medical order alias':'医嘱项别名',
                dataIndex: 'medAlias',
                editable: true,
                width: '150px',
                align: 'center'
            },
            {
                title: this.state.language.language == 'EN'?'operating':'操作',
                dataIndex: 'operation',
                width: '130px',
                align: 'center',
                render: (text, record) => {
                    const { editingKey } = this.state;
                    const editable = this.isEditing(record);
                    return editable ? (
                        <span>
                            <EditableContext.Consumer>
                                {form => (
                                    <span
                                        className="span"
                                        onClick={() => this.handleSave(form, record.key)}
                                    >
                                        {this.state.language.language == 'EN'?'save':'保存'}
                                    </span>
                                )}
                            </EditableContext.Consumer>
                            <Divider type="vertical" />
                            <Popconfirm title= {this.state.language.language == 'EN'?'Do you cancel editing?':"是否取消编辑?"} okText={this.state.language.language == 'EN' ? "Yes" : '是'} cancelText={this.state.language.language == 'EN' ? "No" : '否'} onConfirm={() => this.handleCancel(record)}>
                                <span className="span" style={{color: 'rgba(240,65,52,1)'}}> {this.state.language.language == 'EN'?'cancel':'取消'}</span>
                            </Popconfirm>
                        </span>
                    ) : (
                        <span>
                            <a disabled={editingKey !== ''} onClick={() => this.handleEdit(record.key)}>
                                 {this.state.language.language == 'EN'?'edit':'编辑'}
                            </a>
                            <Divider type="vertical" />
                            <Popconfirm title= {this.state.language.language == 'EN'?'Delete is not recoverable, are you sure you want to delete it?':'"删除不可恢复，你确定要删除吗?"'}  okText={this.state.language.language == 'EN' ? "Yes" : '是'} cancelText={this.state.language.language == 'EN' ? "No" : '否'} onConfirm={() => this.handleDelete(record)}>
                                <span className="span" style={{color: 'rgba(240,65,52,1)'}}> {this.state.language.language == 'EN'?'delete':'删除'}</span>
                            </Popconfirm>
                        </span>
                    );
                },
            },
        ];
        this.setState({columns})
    }

    isEditing = record => record.key === this.state.editingKey;

    // checkAttributeIsEmpty = (obj) => {
    //     let status = false;
    //     for (let key of Object.keys(obj)) {
    //         if (!obj[key]) {
    //             status = true;
    //             break;
    //         }
    //     }
    //     return status
    // }

    // 取消
    handleCancel = (record) => {
        let status =  Util.checkAttributeIsEmpty(this.props.form.getFieldsValue());
        if (status) {
            // 都为空则删除该条记录
            this.setState({editingKey: ''}, () => {
                this.handleDelete(record);
            })
        } else {
            this.setState({editingKey: ''})
        }
    };
  
    // 保存
    handleSave = (form, key) => {
        form.validateFields((error, row) => {
            if (error) {
                return;
            }
            const newData = [...this.state.dataSource];
            const index = newData.findIndex(item => key === item.key);
            if (index > -1) {
                const item = newData[index];
                newData.splice(index, 1, {
                    ...item,
                    ...row,
                });
                this.setState({ dataSource: newData, editingKey: '' }, () => {
                    this.props && this.props.handleSave && this.props.handleSave();
                });
            } else {
                newData.push(row);
                this.setState({ dataSource: newData, editingKey: '' }, () => {
                    this.props && this.props.handleSave && this.props.handleSave();
                });
            }
        });
    }
  
    // 编辑
    handleEdit = (key) => {
        this.setState({ editingKey: key });
    }

    // 本地删除数据
    deleteRow(key){
        const dataSource = JSON.parse(JSON.stringify(this.state.dataSource));
        this.setState({ dataSource: dataSource.filter(item => item.key !== key)});
    }
  
    // 删除
    handleDelete = (record) => {
        let isSaveAnother = this.props.isSaveAnother;
        if (record.aliasID && isSaveAnother !== "saveAnother") {
            let data ={
                params: [
                    {
                        medAliasID: record.aliasID,
                    }
                ]
            }
            $http.post('urlS', this, {
                code: "02020228",
                data: data,
                success: function (res) {
                    if (+res.errorCode === 0) {
                        message.success(res.errorMessage);
                        this.deleteRow(record.key);
                    }
                }
            })
        } else {
            this.deleteRow(record.key)
        }
    }

    // 新增表格数据
    handleAddTableData = () => {
        const { dataSource } = this.state;
        let leg = dataSource&&dataSource.length ? dataSource.length + 1 : 1;
        let arr = [];
        const newData = {
            key: leg,
            medAlias: '',
        };
        arr.push(newData)
        this.setState({
            dataSource: dataSource&&dataSource.length> 0 ? [...dataSource, newData] : arr
        }, () => {
            if (!this.state.editingKey) {
                this.setState({editingKey: leg})
            }
        });
    }

    // 重置数据
    resetFields = () => {
        this.setState({dataSource: [], editingKey: ''})
    }

    resetFieldsEditingKey = () => {
        this.setState({editingKey: ''})
    }

    handleOnRow = (record) => {
        return {
            onDoubleClick: () => {
                this.props.form.resetFields();
                this.setState({ editingKey: record.key });
            }
        }
    }
    
    render() {
        let {dataSource, columns} = this.state;
        const components = {
            body: {
                cell: EditableCell,
            },
        };
        const filterColumns = columns.map(col => {
            if (!col.editable) {
                return col;
            }
            return {
                ...col,
                onCell: record => ({
                    record,
                    inputType: col.dataIndex === 'age' ? 'select' : 'text',
                    dataIndex: col.dataIndex,
                    title: col.title,
                    editing: this.isEditing(record),
                }),
            };
        });
        let  ChineseEnglishSize=this.props.ChineseEnglishSize;
        return (
            <Card
                type="inner"
                title={<div style={{position: 'relative'}}>
                    {ChineseEnglishSize.DrugMaintenanceorderItemAlias ? ChineseEnglishSize.DrugMaintenanceorderItemAlias.descripts:'医嘱项别名'}
                    <span style={{position: 'absolute', top: '-6px', right: '4px'}}><Button onClick={this.handleAddTableData}> {ChineseEnglishSize.DrugMaintenanceadd ? ChineseEnglishSize.DrugMaintenanceadd.descripts:'新增'}</Button></span>
                </div>}
                size="small"
                
            >
                <div style={{padding: '8px 15px'}}>
                    <EditableContext.Provider value={this.props.form}>
                        <Table
                            style={{minHeight: '220px'}}
                            components={components}
                            bordered
                            dataSource={dataSource}
                            columns={filterColumns}
                            rowClassName="editable-row"
                            pagination={{
                                onChange: this.handleCancel,
                            }}
                            onRow={this.handleOnRow}
                        />
                    </EditableContext.Provider>
                </div>
            </Card>
        )
    }
};
let ADADoctorAdviceAliasForm = Form.create()(ADADoctorAdviceAlias);
export default ADADoctorAdviceAliasForm;
